package com.ezops.poc.processor;

import java.util.ArrayList;
import java.util.List;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ezops.poc.bo.ClientTradeModel;
import com.ezops.trade.processing.partners.orchestrade.OrchesTradeModel;

@Component(value = "splitProcessor")
public class TradeSplitProcessor implements Processor {
	@Autowired
	protected ProducerTemplate producer;

	@Override
	public void process(Exchange exchange) throws Exception {

		List<OrchesTradeModel> validTrades = new ArrayList<>();
		List<ClientTradeModel> invalidTrades = new ArrayList<>();

		/**
		 * If multiple records are there the body will have List
		 */
		if (exchange.getIn().getBody() instanceof List) {

			List aggregatedTrades = exchange.getIn().getBody(List.class);

			for (Object trade : aggregatedTrades) {
				if (trade instanceof ClientTradeModel) {
					invalidTrades.add((ClientTradeModel) trade);
				} else {
					validTrades.add((OrchesTradeModel) trade);
				}
			}
			if (validTrades != null && !validTrades.isEmpty()) {
				exchange.getIn().setBody(validTrades);
				producer.send("direct:validfile", exchange);
			}
			if (invalidTrades != null && !invalidTrades.isEmpty()) {
				exchange.getIn().setBody(invalidTrades);
				producer.send("direct:errors", exchange);
			}
		} else if (exchange.getIn().getBody() instanceof OrchesTradeModel) {
			OrchesTradeModel trade = exchange.getIn().getBody(
					OrchesTradeModel.class);
			validTrades.add(trade);
			exchange.getIn().setBody(validTrades);
			producer.send("direct:validfile", exchange);
		} else {
			ClientTradeModel trade = exchange.getIn().getBody(
					ClientTradeModel.class);
			invalidTrades.add(trade);
			exchange.getIn().setBody(invalidTrades);
			producer.send("direct:errors", exchange);
		}

	}

}
